package com.bsoft.gol.hcb.service.feedback.dao;

import com.bsoft.gol.hcb.service.feedback.entity.BaseFeedback;
import com.bsoft.gol.hcb.utils.CommonUtils;
import com.bsoft.gol.hcb.utils.DateUtils;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import hcn.bean.feedback.qo.FeedbackListReq;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author:FangZhiyi
 * @Description
 * @Data Created in 2020/8/20 11:32
 * @Moddified By:
 */
public abstract class BaseFeedbackDAO extends HibernateSupportDelegateDAO<BaseFeedback> {
    public Long queryFeedbackListCount(FeedbackListReq feedbackListReq) {
        HibernateStatelessResultAction<Long> action = new AbstractHibernateStatelessResultAction<Long>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDocFeedbackListCountStringBuffer(feedbackListReq);
                Query sqlQuery = getQuery(ss, feedbackListReq, stringBuffer);
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                if (CommonUtils.isNotEmpty(dbList)) {
                    setResult(Long.valueOf(String.valueOf(dbList.get(0).get("countValue"))));
                } else {
                    setResult(0L);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    public List<BaseFeedback> queryDocFeedbackList(FeedbackListReq feedbackListReq) {
        HibernateStatelessResultAction<List<BaseFeedback>> action = new AbstractHibernateStatelessResultAction<List<BaseFeedback>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDocFeedbackListStringBuffer(feedbackListReq);
                Query sqlQuery = getQuery(ss, feedbackListReq, stringBuffer);
                int first = feedbackListReq.getPageNo() > 0 ? (feedbackListReq.getPageNo() - 1) * feedbackListReq.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(feedbackListReq.getPageSize());
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                setResult(mapToList(dbList));
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private StringBuffer getDocFeedbackListCountStringBuffer(FeedbackListReq feedbackListReq) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT count(1 ) countValue  from base_feedback  where 1=1");
        return getDocFeedbackListWhereStringBuffer(feedbackListReq,stringBuffer);
    }

    private StringBuffer getDocFeedbackListStringBuffer(FeedbackListReq feedbackListReq) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT feedback_id feedbackId, user_id userId, user_name userName, role_type roleType,")
                .append("content content, organization_id organizationId, organization_name organizationName,")
                .append("reply_user_id replyUserId, reply_user_name replyUserName, reply_content replyContent,")
                .append("reply_time replyTime, status status, classify classify, classify_name classifyName,avatar avatar,")
                .append("phone_follow_up_flag phoneFollowUpFlag,phone_no phoneNo,operators operators,os_version osVersion,")
                .append("app_version appVersion, device_unique_code deviceUniqueCode,gmt_create gmtCreate ")
                .append("from base_feedback  where 1=1");
        return getDocFeedbackListWhereStringBuffer(feedbackListReq,stringBuffer);
    }

    private StringBuffer getDocFeedbackListWhereStringBuffer(FeedbackListReq feedbackListReq, StringBuffer stringBuffer){
        if (StringUtils.isNotEmpty(feedbackListReq.getUserId())) {
            stringBuffer.append(" and user_id=:userId");
        }
        if (StringUtils.isNotEmpty(feedbackListReq.getContent())) {
            stringBuffer.append(" and content like :content");
        }
        if (StringUtils.isNotEmpty(feedbackListReq.getOrganizationId())) {
            stringBuffer.append(" and organization_id=:organizationId");
        }
        if (CommonUtils.isNotEmpty(feedbackListReq.getOrganizationIdList())) {
            stringBuffer.append(" and organization_id in(:organizationIdList)");
        }
        if (StringUtils.isNotEmpty(feedbackListReq.getStatus())&&!"9".equals(feedbackListReq.getStatus())) {
            stringBuffer.append(" and status=:status");
        }
        if (CollectionUtils.isNotEmpty(feedbackListReq.getClassifyList())) {
            stringBuffer.append(" and classify in (");
            for (String classify:feedbackListReq.getClassifyList()) {
                stringBuffer.append(classify).append(",");
            }
            stringBuffer.append("0)");
        }
        if (feedbackListReq.getStartTime()!=null) {
            stringBuffer.append(" and gmt_create>=:startTime");
        }
        if (feedbackListReq.getEndTime()!=null) {
            stringBuffer.append(" and gmt_create<=:endTime");
        }
        stringBuffer.append(" ORDER BY gmt_create DESC");
        return stringBuffer;
    }

    private Query getQuery(StatelessSession ss, FeedbackListReq feedbackListReq, StringBuffer stringBuffer) {
        Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
        if (StringUtils.isNotEmpty(feedbackListReq.getUserId())) {
            sqlQuery.setParameter("userId", feedbackListReq.getUserId());
        }
        if (StringUtils.isNotEmpty(feedbackListReq.getContent())) {
            sqlQuery.setParameter("content", "%" + feedbackListReq.getContent() + "%");
        }

        if (StringUtils.isNotEmpty(feedbackListReq.getOrganizationId())) {
            sqlQuery.setParameter("organizationId", feedbackListReq.getOrganizationId());
        }
        if (CommonUtils.isNotEmpty(feedbackListReq.getOrganizationIdList())) {
            sqlQuery.setParameterList("organizationIdList", feedbackListReq.getOrganizationIdList());
        }
        if (StringUtils.isNotEmpty(feedbackListReq.getStatus()) && !"9".equals(feedbackListReq.getStatus())) {
            sqlQuery.setParameter("status", feedbackListReq.getStatus());
        }
        if (feedbackListReq.getStartTime() != null) {
            sqlQuery.setParameter("startTime", DateUtils.dateFormate(feedbackListReq.getStartTime(), "yyyy-MM-dd") + " 00:00:00");
        }
        if (feedbackListReq.getEndTime() != null) {
            sqlQuery.setParameter("endTime", DateUtils.dateFormate(feedbackListReq.getEndTime(), "yyyy-MM-dd") + " 23:59:59");
        }
        return sqlQuery;
    }

    private List<BaseFeedback> mapToList(List<Map> maps) {
        List<BaseFeedback> feedbackList = new ArrayList<>();
        for (Map map : maps) {
            feedbackList.add(ConversionUtils.convert(map, BaseFeedback.class));
        }
        return feedbackList;
    }
}
